﻿using System.Text.Json.Serialization;
using BCore.Identity.Users.Caching;
using Core.Caching;
using Core.Helpers;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Users.Features.Commands.Enable;

/// <summary>
///  启用/禁用角色
/// </summary>
public class SetUserEnabledStatusCommand : ICacheInvalidatorRequest<Result<bool>>
{
    /// <summary>
    /// 角色唯一标识
    /// </summary>
    public Guid Id { get; set; }

    /// <summary>
    /// 设置启用/禁用
    /// </summary>
    public bool Enabled { get; set; }

    [JsonIgnore]
    public IEnumerable<string>? Tags => UsersCacheKey.Tags;
}

public class SetUserEnabledStatusCommandHandler(IIdentityDbContext dbContext) : IRequestHandler<SetUserEnabledStatusCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(SetUserEnabledStatusCommand request, CancellationToken cancellationToken)
    {
        var user = await dbContext.Users
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);
        ExceptionHelper.ThrowIfNull(user, "数据不存在");

        user!.SetEnabled(request.Enabled);

        dbContext.Users.Update(user);

        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;
        return await Result<bool>.SucceedAsync(result, result, ["修改失败"]);
    }
}
